package com.example.housebiz.service;

import com.example.housebiz.mapper.UserMapper;
import com.example.housecommon.model.User;
import com.example.housecommon.utils.BeanHelper;
import com.example.housecommon.utils.HashUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-05-27
 **/
@Service
public class UserService {


    @Value("${domain.name:}")
    private String domainName;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private FileService fileService;


    @Autowired
    private MailService mailService;

    @Value("${img.prefix}")
    private String imgPrefix;


    private final Cache<String,String> registerCache = CacheBuilder.newBuilder().maximumSize(100).expireAfterAccess(15, TimeUnit.MINUTES)
            .removalListener(new RemovalListener<String, String>() {
                @Override
                public void onRemoval(RemovalNotification<String, String> removalNotification) {
                    userMapper.delete(removalNotification.getValue());
                }
            }).build();

    /**
     * 1.插入数据库 非激活;密码加盐md5 保存头像到本地
     * 2.生成key，绑定email
     * 3.发送邮件给用户
     * @param account
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addAccount(User account) {
        account.setPasswd(HashUtils.encryPassword(account.getPasswd()));
        if(!(account.getAvatarFile()== null)){
            List<String> imgList = fileService.getImgPaths(Lists.newArrayList(account.getAvatarFile()));
            if (!imgList.isEmpty()) {
                account.setAvatar(imgList.get(0));
            }
        }
        BeanHelper.setDefaultProp(account, User.class);
        BeanHelper.onInsert(account);
        account.setEnable(0);
        userMapper.insert(account);
        registerNotify(account.getEmail());
        return true;
    }


    /**
     * 1.缓存key-email的关系
     * 2.借助spring mail发送邮件
     * 3.借助异步框架进行异步操作
     * @param email
     */
    private void registerNotify(String email) {
        String randomKey = RandomStringUtils.randomAlphabetic(10);
        registerCache.put(randomKey,email);
        String url = "http://"+domainName+"/accounts/verify?key="+randomKey;
        mailService.sendMail("房产平台激活邮件",url,email);
    }


    public boolean enable(String key) {
        String email = registerCache.getIfPresent(key);
        if(StringUtils.isBlank(email)){
            return false;
        }
        User updateUser = new User();
        updateUser.setEnable(1);
        updateUser.setEmail(email);   //要根据email来判断更新哪个user where email = #{email}
        userMapper.update(updateUser);
        registerCache.invalidate(key);
        return true;
    }


    /**
     * 用户名密码验证
     * @param username
     * @param password
     * @return
     */
    public User auth(String username,String password) {
        User user = new User();
        user.setName(username);
        user.setPasswd(HashUtils.encryPassword(password));
        user.setEnable(1);
        List<User> list = getUserByQuery(user);
        if(! list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }


    public List<User> getUserByQuery(User user) {
        List<User> userList = userMapper.selectUsersByQuery(user);
        userList.forEach(u->{
            u.setAvatar(imgPrefix+u.getAvatar());   //给图片加上ngnix prefix
        });
        return userList;
    }

    public void updateUser(User updateUser,String name) {
        updateUser.setName(name);
        BeanHelper.onUpdate(updateUser);
        userMapper.update(updateUser);
    }
}


